import React, { useState, useEffect } from "react";
// import Header from "../../components/Header"
// import "./index.scss"
let websock = null;

export default function App(props) {
  let [dataname, setDataname] = useState("");
  let img =
    "https://up.enterdesk.com/edpic/de/58/84/de5884d372b9ee2fe137c6501326ff85.jpg";
  useEffect(() => {
    const wsuri = "ws://localhost:9990";
    websock = new WebSocket(wsuri);
    initWebSocket(websock);
    return () => websocketclose();
  }, []);

  //发送
  function getdata() {
    if (dataname !== "") {
      let doxs = document.querySelector(".dox");
      const div = document.createElement("li");
      div.innerHTML =
        `<div class = 'li'><img src=${img} /></span><p  > ` +
        dataname +
        "</p></div>";
      doxs.appendChild(div);
      websocketsend(
        JSON.stringify({
          text: dataname,
          img: img,
          name: "111",
        })
      );
      setDataname("");
      let dox = document.getElementsByClassName("main")[0];
      let lis = document.getElementsByTagName("LI");
      dox.scrollTop = lis[lis.length - 1].offsetTop;
    }
  }
  let initWebSocket = () => {
    //初始化weosocket
    websock.onmessage = websocketonmessage;
    websock.onopen = websocketonopen;
    websock.onerror = websocketonerror;
    websock.onclose = websocketclose;
  };
  function websocketonopen() {
    //连接建立之后执行send方法发送数据
    if (websock.readyState === 1) {
      console.log("连接成功");
    }
  }
  function websocketonerror() {
    //连接建立失败重连
    initWebSocket();
  }
  //接收
  function websocketonmessage(msg) {
    //数据接收
    let { text } = JSON.parse(msg.data);
    let doxs = document.querySelector(".dox");
    const div = document.createElement("li");
    div.innerHTML =
      `<div class = 'lis'><img src='https://img1.baidu.com/it/u=3254254623,2492769581&fm=26&fmt=auto&gp=0.jpg'/><p>` +
      text +
      "</p></div>";
    doxs.appendChild(div);
    let dox = document.getElementsByClassName("main")[0];
    let lis = document.getElementsByTagName("LI");
    dox.scrollTop = lis[lis.length - 1].offsetTop;
  }
  let websocketsend = (Data) => {
    //数据发送
    websock.send(Data);
  };

  function websocketclose(e) {
    //关闭
    console.log("断开连接", e);
  }
  return (
    <div className="service">
      {/* <Header {...props} title={props.location.state.name} /> */}
      <main className="main">
        <ul className="dox"></ul>
      </main>
      <footer>
        <input
          type="text"
          placeholder="请输入要说的话"
          value={dataname}
          onChange={(e) => {
            setDataname(e.target.value);
          }}
          onKeyDown={(e) => {
            if (e.keyCode === 13) {
              getdata();
            }
          }}
        />
        <button
          onClick={() => {
            getdata();
          }}
        >
          发送
        </button>
      </footer>
    </div>
  );
}
